import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Row, Col } from 'antd';
import moment from 'moment';
import AntdDatePicker from '@/components/AntdDatePicker';
import EditPage from '@/components/EditPage';
import AntdForm from '@/components/AntdForm';
import AdSelect from '@/components/AdSelect';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import AdInput from '@/components/AdInput';
import AdSearch from '@/components/AdSearch';
import prompt from '@/components/Prompt';
import AdButton from '@/components/AdButton';
import { editCol, editGutter, editRow } from '@/utils/constans';
import { queryDictData, queryPerson } from '@/utils/common';
import { plateList, dateFormat, driversColumns } from './utils';
import VehicleInfo from './VehicleInfo';
const FormItem = Form.Item;

@connect(({ vehicle, component }) => ({
  vehicleDetail: vehicle.vehicleDetail,
  ownCompany: component.ownCompany,
  dictObject: component.dictObject,
  formValues: vehicle.formValues,
}))
@Form.create()
export default class VehicleOperate extends Component {
  state = {
    detailId: '',
    visible: false,
  };

  componentWillMount() {
    const { dictObject, dispatch, ownCompany } = this.props;
    queryDictData({
      dispatch,
      type: 'component/queryOwnCompany',
      isExist: ownCompany.length > 0,
    });
    const allDict = [
      'vehicle_category',
      'vehicle_type',
      'coach',
      'vehicle_properties',
      'vehicle-papers-type',
    ];
    allDict.map(v => {
      queryDictData({
        dispatch,
        payload: { code: v },
        isExist: dictObject[v],
      });
    });
  }

  componentDidMount() {
    const {
      match: {
        params: { id },
      },
      vehicleDetail,
      dispatch,
    } = this.props;
    if (!id) return;
    this.setState({ detailId: id });
    if (vehicleDetail[id]) {
      this.setTabName({ id, name: vehicleDetail[id].cartPlateOneNo });
    } else {
      dispatch({
        type: 'vehicle/vehicleDetail',
        payload: { id },
        callback: data => {
          if (!data) return;
          this.setTabName({
            id,
            name: data.cartPlateOneNo,
          });
        },
      });
    }
  }

  setTabName = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/setTabsName',
      payload,
      // callback: data,
    });
  };

  selectVehicleList = ({ payload = {} } = {}) => {
    const { dispatch, searchValue } = this.props;
    dispatch({
      type: 'vehicle/selectVehicleList',
      payload,
      callback: data => {
        if (!data) return;
        queryPerson({ data, searchValue, dispatch });
      },
    });
  };

  /**
   * 保存数据
   */
  saveInfo = () => {
    const { form, dispatch, vehicleDetail, formValues } = this.props;
    const { detailId } = this.state;
    const detail = vehicleDetail[detailId];
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      const {
        drivers,
        cartPlateTypeOne,
        cartPlateTypeTwo,
        cartPlateOneNo,
        cartPlateTwoNo,
        certificateTime,
        registerTime,
        ...payload
      } = values;
      if (certificateTime) {
        payload.certificateTime = moment(certificateTime).format(dateFormat);
      }
      if (registerTime) {
        payload.registerTime = moment(registerTime).format(dateFormat);
      }
      payload.cartPlateTwoNo =
        cartPlateTypeTwo == '港澳牌'
          ? cartPlateTwoNo
          : cartPlateTypeTwo
          ? cartPlateTypeTwo + cartPlateTwoNo
          : cartPlateTwoNo;

      if (detailId !== '') {
        payload.id = detailId;
        payload.deleteDriverIds = detail.drivers
          .filter(item => !drivers.map(v => v.id).includes(item.id))
          .map(v => v.id);
        payload.driverIds = drivers
          .filter(item => !detail.drivers.map(v => v.id).includes(item.id))
          .map(v => v.id);
      } else {
        if (cartPlateTypeOne) {
          payload.cartPlateOneNo =
            cartPlateTypeOne == '港澳牌'
              ? cartPlateOneNo
              : cartPlateTypeOne
              ? cartPlateTypeOne + cartPlateOneNo
              : cartPlateOneNo;
        } else {
          prompt({ title: '温馨提示', content: '请选择主车牌', type: 'warn' });
          return;
        }
      }
      dispatch({
        type: 'vehicle/vehicleOperate',
        payload,
        callback: data => {
          if (!data) return;
          this.selectVehicleList({ payload: formValues });
          dispatch({
            type: 'vehicle/vehicleDetail',
            payload: { id: data },
            callback: res => {
              if (!res) return;

              if (detailId === '') {
                this.setTabName({
                  id: data,
                  isReplaceTab: true,
                  name: res.cartPlateOneNo,
                  callback: result => {
                    if (result) {
                      router.push(`/manageCar/vehicleList/edit-form/${data}`);
                    }
                  },
                });
              }
            },
          });
        },
      });
    });
  };

  infoAdd = e => {
    e.stopPropagation();
    const { detailId } = this.props;
    if (!detailId) {
      prompt({ content: '请先新增车辆，再新增证件', type: 'warn' });
    } else {
      this.setInfoModal();
    }
  };

  setInfoModal = () => {
    const { visible } = this.state;
    this.setState({ visible: !visible });
  };

  render() {
    const { detailId, visible } = this.state;
    const {
      form: { getFieldDecorator },
      vehicleDetail,
      ownCompany,
      dictObject,
    } = this.props;
    const detail = vehicleDetail[detailId];
    const editPageParams = {
      title: detail ? detail.cartPlateOneNo : '新增车辆',
      saveInfo: this.saveInfo,
      panelTitle: ['基础信息', '证件信息'],
      extra: {
        1: <AdButton type="primary" onClick={this.infoAdd} text="新增"></AdButton>,
      },
    };
    const commonParams = {
      getFieldDecorator,
    };

    const prefixSelector = (name, type) => (
      <AntdFormItem code={name} initialValue={undefined} {...commonParams}>
        <AdSelect
          data={plateList}
          isExist={true}
          allowClear={type == 2 ? true : false}
          show={{ id: 'key', name: 'val' }}
          style={{ width: 120 }}
        />
      </AntdFormItem>
    );

    const formItem = [
      [
        <AntdFormItem
          label="主车牌"
          code="cartPlateOneNo"
          rules={[{ required: true }]}
          initialValue={detail ? detail.cartPlateOneNo : ''}
          {...commonParams}
        >
          {detail ? (
            <AntdInput disabled={true} />
          ) : (
            <AntdInput addonBefore={prefixSelector('cartPlateTypeOne', 1)} />
          )}
        </AntdFormItem>,
        <AntdFormItem
          label="副车牌"
          code="cartPlateTwoNo"
          initialValue={detail ? detail.cartPlateTwoNo : ''}
          {...commonParams}
        >
          {detail ? (
            <AntdInput disabled={true} />
          ) : (
            <AntdInput addonBefore={prefixSelector('cartPlateTypeTwo', 2)} />
          )}
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="公司"
          code="ownCompanyId"
          rules={[{ required: true }]}
          initialValue={detail ? detail.ownCompanyId : undefined}
          {...commonParams}
        >
          <AdSelect
            data={ownCompany}
            url="mds/d-customer/selectCompany"
            show={{ id: 'customerCode', name: 'customerName' }}
          />
        </AntdFormItem>,
        <AntdFormItem
          label="属性"
          code="property"
          rules={[{ required: true }]}
          initialValue={detail ? detail.property : undefined}
          {...commonParams}
        >
          <AdSelect
            data={dictObject['vehicle_properties']}
            payload={{ code: 'vehicle_properties' }}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="分类"
          code="category"
          rules={[{ required: true }]}
          initialValue={detail ? detail.category : undefined}
          {...commonParams}
        >
          <AdSelect data={dictObject['vehicle_category']} payload={{ code: 'vehicle_category' }} />
        </AntdFormItem>,
        <AntdFormItem
          label="车辆类型"
          code="cartType"
          rules={[{ required: true }]}
          initialValue={detail ? detail.cartType : undefined}
          {...commonParams}
        >
          <AdSelect data={dictObject['vehicle_type']} payload={{ code: 'vehicle_type' }} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="所有人"
          code="ownPersonName"
          initialValue={detail ? detail.ownPersonName : ''}
          {...commonParams}
        >
          <AntdInput />
        </AntdFormItem>,
        <AntdFormItem
          label="品牌型号"
          code="brandModel"
          initialValue={detail ? detail.brandModel : ''}
          {...commonParams}
        >
          <AntdInput />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="识别代号"
          code="recognizeNo"
          initialValue={detail ? detail.recognizeNo : ''}
          {...commonParams}
        >
          <AntdInput />
        </AntdFormItem>,
        <AntdFormItem
          label="发动机号码"
          code="engineNo"
          initialValue={detail ? detail.engineNo : ''}
          {...commonParams}
        >
          <AntdInput />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="车厢"
          code="coach"
          initialValue={detail ? detail.coach : undefined}
          {...commonParams}
        >
          <AdSelect data={dictObject['coach']} payload={{ code: 'coach' }} />
        </AntdFormItem>,
        <FormItem label="车厢尺寸(MM)">
          <Row gutter={8}>
            {[
              { code: 'coachInnerLength', placeholder: '长' },
              { code: 'coachInnerWidth', placeholder: '宽' },
              { code: 'coachInnerHigh', placeholder: '高' },
            ].map(v => {
              return (
                <Col span={8} key={v.code}>
                  <AntdFormItem
                    code={v.code}
                    initialValue={detail ? detail[v.code] : ''}
                    {...commonParams}
                  >
                    <AntdInput placeholder={v.placeholder} />
                  </AntdFormItem>
                </Col>
              );
            })}
          </Row>
        </FormItem>,
      ],
      [
        <FormItem label="外廓尺寸(MM)">
          <Row gutter={8}>
            {[
              { code: 'gabariteLenght', placeholder: '长' },
              { code: 'gabariteWidth', placeholder: '宽' },
              { code: 'gabariteHigh', placeholder: '高' },
            ].map(v => {
              return (
                <Col span={8} key={v.code}>
                  <AntdFormItem
                    code={v.code}
                    initialValue={detail ? detail[v.code] : ''}
                    {...commonParams}
                  >
                    <AntdInput placeholder={v.placeholder} />
                  </AntdFormItem>
                </Col>
              );
            })}
          </Row>
        </FormItem>,
        <AntdFormItem
          label="车辆总质量(KG)"
          code="totalWeight"
          initialValue={detail ? detail.totalWeight : ''}
          {...commonParams}
        >
          <AntdInput />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="准牵引总质量(KG)"
          code="accuratePullWeight"
          initialValue={detail ? detail.accuratePullWeight : ''}
          {...commonParams}
        >
          <AntdInput />
        </AntdFormItem>,
        <AntdFormItem
          label="整备质量(KG)"
          code="reconditionWeight"
          initialValue={detail ? detail.reconditionWeight : ''}
          {...commonParams}
        >
          <AntdInput />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="核实载质量(KG)"
          code="realHoldWeight"
          initialValue={detail ? detail.realHoldWeight : ''}
          {...commonParams}
        >
          <AntdInput />
        </AntdFormItem>,
        <AntdFormItem
          label="注册日期"
          code="registerTime"
          initialValue={
            detail && detail.registerTime ? moment(detail.registerTime, dateFormat) : null
          }
          {...commonParams}
        >
          <AntdDatePicker />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="发证日期"
          code="certificateTime"
          initialValue={
            detail && detail.certificateTime ? moment(detail.certificateTime, dateFormat) : null
          }
          {...commonParams}
        >
          <AntdDatePicker />
        </AntdFormItem>,
        <FormItem label="百公里平均油耗">
          <Row gutter={8}>
            <Col span={11}>
              <AntdFormItem
                code="hundredExpendMin"
                initialValue={detail ? detail.hundredExpendMin : ''}
                {...commonParams}
              >
                <AntdInput placeholder="min" />
              </AntdFormItem>
            </Col>
            <Col span={2}>~</Col>
            <Col span={11}>
              <AntdFormItem
                code="hundredExpendMax"
                initialValue={detail ? detail.hundredExpendMax : ''}
                {...commonParams}
              >
                <AntdInput placeholder="max" />
              </AntdFormItem>
            </Col>
          </Row>
        </FormItem>,
      ],
      [
        <AntdFormItem
          label="车辆价格"
          code="cartPrice"
          initialValue={detail ? detail.cartPrice : ''}
          {...commonParams}
        >
          <AntdInput />
        </AntdFormItem>,
        <AntdFormItem
          label="保养公里(KM)"
          code="upkeepKm"
          initialValue={detail ? detail.upkeepKm : ''}
          {...commonParams}
        >
          <AntdInput />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="保养周期(月)"
          code="upkeepCycle"
          initialValue={detail ? detail.upkeepCycle : ''}
          {...commonParams}
        >
          <AntdInput />
        </AntdFormItem>,
        <AntdFormItem
          label="司机"
          code="drivers"
          initialValue={detail ? detail.drivers : undefined}
          {...commonParams}
        >
          <AdSearch
            dataUrl="tms/tms-driver/selectList"
            columns={driversColumns}
            id="vehicle-operate"
            scrollX={500}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="备注"
          code="remarks"
          initialValue={detail ? detail.remarks : ''}
          {...commonParams}
        >
          <AntdInput rows={4} mode="eara" />
        </AntdFormItem>,
      ],
    ];

    return (
      <EditPage {...editPageParams}>
        <AntdForm>
          {formItem.map((item, index) => {
            return (
              <Row gutter={editGutter} key={index}>
                {item.map((v, i) => {
                  const colSpan = item.length === 1 ? editRow : editCol;
                  return (
                    <Col {...colSpan} key={index + i}>
                      {v}
                    </Col>
                  );
                })}
              </Row>
            );
          })}
        </AntdForm>
        <VehicleInfo detailId={detailId} visible={visible} setInfoModal={this.setInfoModal} />
      </EditPage>
    );
  }
}
